package com.talent.jiwen.my;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.talent.jiwen.IndexActivity;
import com.talent.jiwen.R;
import com.talent.jiwen.base.BaseActivity;
import com.talent.jiwen.http.common.ActivityLifeCycleEvent;
import com.talent.jiwen.http.common.ApiFactory;
import com.talent.jiwen.http.common.HttpUtil;
import com.talent.jiwen.http.common.ProgressSubscriber;
import com.talent.jiwen.http.result.AliPayResult;
import com.talent.jiwen.http.result.PayInfo;
import com.talent.jiwen.http.result.PayResult;
import com.talent.jiwen.http.result.WXPayResult;
import com.talent.jiwen.http.result.WeChatPayInfo;
import com.talent.jiwen.teacher.CourseAllListFragment;
import com.talent.jiwen.teacher.CourseWaitListFragment;
import com.talent.jiwen.util.Constant;
import com.talent.jiwen.util.DateUtils;
import com.talent.jiwen.util.ImageUtil;
import com.talent.jiwen.util.LogUtil;
import com.talent.jiwen.util.SPUtil;
import com.talent.jiwen.util.Validators;
import com.talent.jiwen.util.WXPayUtils;
import com.talent.jiwen.util.downtime.DownTimer;
import com.talent.jiwen.util.downtime.DownTimerListener;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Observable;


/**
 * Created by qyqx on 2018/8/10.
 * 支付界面
 */

public class PayActivity extends BaseActivity implements DownTimerListener {

    @BindView(R.id.min_1)
    TextView min_1;
    @BindView(R.id.min_2)
    TextView min_2;
    @BindView(R.id.sec_1)
    TextView sec_1;
    @BindView(R.id.sec_2)
    TextView sec_2;
    @BindView(R.id.img_head)
    ImageView img_head;
    @BindView(R.id.txt_teacher)
    TextView txt_teacher;
    @BindView(R.id.txt_use_time)
    TextView txt_use_time;
    @BindView(R.id.txt_pay)
    TextView txt_pay;
    @BindView(R.id.ll_account)
    RelativeLayout ll_account;
    @BindView(R.id.choose_account)
    ImageView choose_account;
    @BindView(R.id.accountMoneyTv)
    TextView accountMoneyTv;
    @BindView(R.id.ll_wechat)
    RelativeLayout ll_wechat;
    @BindView(R.id.choose_wechat)
    ImageView choose_wechat;
    @BindView(R.id.ll_alipay)
    RelativeLayout ll_alipay;
    @BindView(R.id.choose_alipay)
    ImageView choose_alipay;
    @BindView(R.id.bt_pay)
    TextView bt_pay;
    @BindView(R.id.payWayLayout)
    LinearLayout payWayLayout;

    private static final String PARAM_ORDER_ID = "RoomId";

    private boolean freeOrder;

    private String TAG_CHECKED="1";
    private int PayStyle=0;

    private static final int WECHAT_PAY=1;
    private static final int ALI_PAY=2;
    private static final int ACCOUNT_PAY = 3;//账户支付


    String orderId;
    DownTimer downTimer;
    @Override
    protected int provideContentViewId() {
        return R.layout.activity_pay;
    }

    @Override
    public String titleName() {
        return "支付订单";
    }

    @Override
    protected void initData() {

        mBtnLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                EventBus.getDefault().post(CourseWaitListFragment.REFRESH_COURSE_WAIT_LIST);
                EventBus.getDefault().post(CourseAllListFragment.REFRESH_COURSE_ALL_LIST);
                intentActivity(IndexActivity.class);
                finish();
            }
        });

        downTimer = new DownTimer();
        downTimer.setListener(this);
        downTimer.startMinDown(15 * 60 * 1000);
        orderId = getIntent().getStringExtra(PARAM_ORDER_ID);
        getOrderDetail(orderId);

    }

    @OnClick({R.id.ll_account, R.id.ll_wechat, R.id.ll_alipay,R.id.bt_pay})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_account:
                if (ll_account.getTag() == null){
                    ll_account.setTag(TAG_CHECKED);
                    ll_wechat.setTag(null);
                    ll_alipay.setTag(null);
                    PayStyle = ACCOUNT_PAY;
                    choose_account.setBackgroundResource(R.mipmap.img_choose);
                    choose_wechat.setBackgroundResource(R.mipmap.img_no_chooae);
                    choose_alipay.setBackgroundResource(R.mipmap.img_no_chooae);
                }else{
                    PayStyle = 0;
                    ll_account.setTag(null);
                    choose_account.setBackgroundResource(R.mipmap.img_no_chooae);
                }
                break;
            case R.id.ll_wechat:
                if(ll_wechat.getTag()==null){
                    ll_wechat.setTag(TAG_CHECKED);
                    ll_alipay.setTag(null);
                    ll_account.setTag(null);
                    PayStyle=WECHAT_PAY;
                    choose_account.setBackgroundResource(R.mipmap.img_no_chooae);
                    choose_wechat.setBackgroundResource(R.mipmap.img_choose);
                    choose_alipay.setBackgroundResource(R.mipmap.img_no_chooae);
                }else{
                    PayStyle=0;
                    ll_wechat.setTag(null);
                    choose_wechat.setBackgroundResource(R.mipmap.img_no_chooae);
                }
                break;
            case R.id.ll_alipay:
                if(ll_alipay.getTag()==null){
                    ll_alipay.setTag(TAG_CHECKED);
                    ll_wechat.setTag(null);
                    ll_account.setTag(null);
                    PayStyle=ALI_PAY;
                    choose_account.setBackgroundResource(R.mipmap.img_no_chooae);
                    choose_wechat.setBackgroundResource(R.mipmap.img_no_chooae);
                    choose_alipay.setBackgroundResource(R.mipmap.img_choose);
                }else{
                    PayStyle=0;
                    ll_alipay.setTag(null);
                    choose_alipay.setBackgroundResource(R.mipmap.img_no_chooae);
                }
                break;
            case R.id.bt_pay:
                if (freeOrder){
                    EventBus.getDefault().post(CourseAllListFragment.REFRESH_COURSE_ALL_LIST);
                    EventBus.getDefault().post(CourseWaitListFragment.REFRESH_COURSE_WAIT_LIST);
                    finish();
                    intentActivity(IndexActivity.class);
                }else{
                    if(PayStyle!=0){
                        if(PayStyle==WECHAT_PAY){
                            wxPay(orderId);
                        }else if (PayStyle == ALI_PAY){
                            aliPay(orderId);
                        }else {
                            accountPay(orderId);
                        }
                    }else{
                        showToast("请先选择支付方式");
                    }
                }

                break;
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        mBtnLeft.performClick();
    }

    private String orderInfo;//订单信息
    private void toAliPay(){
        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(PayActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();


    }


    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(PayActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
//                        EventBus.getDefault().post(CourseAllListFragment.REFRESH_COURSE_ALL_LIST);
//                        finish();
                        EventBus.getDefault().post(CourseAllListFragment.REFRESH_COURSE_ALL_LIST);
                        EventBus.getDefault().post(CourseWaitListFragment.REFRESH_COURSE_WAIT_LIST);
                        finish();
                        intentActivity(IndexActivity.class);
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(PayActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
                default:
                    break;
            }
        };
    };

    /**账户支付
     *
     * @param orderId
     */
    private void accountPay(String orderId){
        Map<String, String> map = new HashMap<>();
        map.put("orderId", orderId);
        Observable observable = ApiFactory.getEducationApiSingleton().studentPayWithBalance(SPUtil.getToken(),map);
        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<Void>(this) {
            @Override
            protected void _onNext(Void v) {
                showToast("支付成功");
                EventBus.getDefault().post(CourseAllListFragment.REFRESH_COURSE_ALL_LIST);
                EventBus.getDefault().post(CourseWaitListFragment.REFRESH_COURSE_WAIT_LIST);
                finish();
                intentActivity(IndexActivity.class);
            }

            @Override
            protected void _onError(String message) {
                showToast(message);
            }
        }, ActivityLifeCycleEvent.DESTROY, lifecycleSubject, true);
    }

    /**微信支付
     *
     * @param orderId
     */
    private void wxPay(String orderId) {
        Map<String, String> map = new HashMap<>();
        map.put("orderId", orderId);
        map.put("studentId", SPUtil.getUserId());
        Observable observable = ApiFactory.getEducationApiSingleton().studentPayWithWeChat(SPUtil.getToken(),map);
        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<WXPayResult>(this) {
            @Override
            protected void _onNext(WXPayResult wxPayResult) {
                if(wxPayResult!=null){
                    Constant.PAY_SCENE_FOR_WX = Constant.WX_PAY_FOR_ORDER;
                    WeChatPayInfo weChatPayInfo=wxPayResult.getWeChatPayInfo();
                    WXPayUtils.WXPayBuilder builder = new WXPayUtils.WXPayBuilder();
                    builder.setAppId(weChatPayInfo.getAppid())
                            .setPartnerId(weChatPayInfo.getPartnerid())
                            .setPrepayId(weChatPayInfo.getPrepayid())
                            .setPackageValue(weChatPayInfo.getPackageValue())
                            .setNonceStr(weChatPayInfo.getNoncestr())
                            .setTimeStamp(weChatPayInfo.getTimestamp())
                            .setSign(weChatPayInfo.getSign())
                            .build().toWXPayNotSign(PayActivity.this);

                }else{
                    showToast("支付失败，请稍后重试");
                }
            }

            @Override
            protected void _onError(String message) {
                showToast(message);
            }
        }, ActivityLifeCycleEvent.DESTROY, lifecycleSubject, false);

    }

    /**支付宝支付
     *
     * @param orderId
     */
    private void aliPay(String orderId) {
        Map<String, String> map = new HashMap<>();
        map.put("orderId", orderId);
        map.put("studentId", SPUtil.getUserId());
        Observable observable = ApiFactory.getEducationApiSingleton().studentPayWithAliPay(SPUtil.getToken(),map);
        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<AliPayResult>(this) {
            @Override
            protected void _onNext(AliPayResult aliPayResult) {
                if(aliPayResult!=null){
                    orderInfo=aliPayResult.getAliPayPrepayId();
                    if(!Validators.isEmpty(orderInfo)){
                        toAliPay();
                    }else{
                        showToast("支付失败，请稍后重试");
                    }
                }else{
                    showToast("支付失败，请稍后重试");
                }
            }
            @Override
            protected void _onError(String message) {
                showToast(message);
            }
        }, ActivityLifeCycleEvent.DESTROY, lifecycleSubject, false);

    }

    /**获取订单详情
     *
     * @param orderId
     */
    private void getOrderDetail(String orderId) {
        Map<String, String> map = new HashMap<>();
        map.put("orderId", orderId);
        map.put("studentId", SPUtil.getUserId());
        Observable observable = ApiFactory.getEducationApiSingleton().getOrderPayInfo(SPUtil.getToken(),map);
        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<PayInfo>(this) {
            @Override
            protected void _onNext(PayInfo payInfo) {
                if (payInfo != null) {
                    ImageUtil.loadImageWithDefault(PayActivity.this,payInfo.getOrderPayInfo().getTeacherHeadImage(),R.mipmap.default_img,img_head);
                    txt_teacher.setText(payInfo.getOrderPayInfo().getTeacherName());
                    try {
                        txt_use_time.setText("课程用时"+ DateUtils.getDatePoor(Long.parseLong(payInfo.getOrderPayInfo().getEndTime())-Long.parseLong(payInfo.getOrderPayInfo().getStartTime())));
                    }catch (Exception e){
                        LogUtil.e(e.toString());
                    }

                    if(Double.parseDouble(payInfo.getTotalAmount()) > Double.parseDouble(payInfo.getOrderPayInfo().getPersonalPrice())){
                        //账户余额大于订单金额，显示账户支付
                        ll_account.setVisibility(View.VISIBLE);
                        accountMoneyTv.setText("余额：" + payInfo.getTotalAmount());
                        //默认账户支付勾选
                        PayStyle = ACCOUNT_PAY;
                        ll_account.setTag(TAG_CHECKED);
                        choose_account.setBackgroundResource(R.mipmap.img_choose);


                    }else{
                        //账户余额不足的时候，直接隐藏账户支付
                        ll_account.setVisibility(View.GONE);
                        PayStyle = 0 ;
                    }

                    switch (payInfo.getOrderPayInfo().getOrderStatus()){
                        case 6:
                            //已完成，未付款
                            freeOrder = false;
                            bt_pay.setText("确认支付");
                            payWayLayout.setVisibility(View.VISIBLE);
                            txt_pay.setText("¥"+payInfo.getOrderPayInfo().getPersonalPrice());
                            break;
                        case 7:
                        case 12:
                            freeOrder = true;
                            bt_pay.setText("完成");
                            payWayLayout.setVisibility(View.GONE);
                            //已付款,免单
                            txt_pay.setText("¥" + payInfo.getOrderPayInfo().getPersonalPrice() +"(免单)");
                            break;
                    }

//                    txt_pay.setText("¥"+payInfo.getOrderPayInfo().getPersonalPrice());
                } else {
                    showToast(getString(R.string.data_is_wrong));
                }
            }

            @Override
            protected void _onError(String message) {
                showToast(message);
            }
        }, ActivityLifeCycleEvent.DESTROY, lifecycleSubject, false);

    }


    @Override
    public void onTick(long millisUntilFinished) {

    }

    @Override
    public void onFinish() {
        showToast("支付超时");
        finish();
    }

    @Override
    public void onMinTick(String str) {
      if(!Validators.isEmpty(str)&& str.length()==5){
          min_1.setText(String.valueOf(str.charAt(0)));
          min_2.setText(String.valueOf(str.charAt(1)));
          sec_1.setText(String.valueOf(str.charAt(3)));
          sec_2.setText(String.valueOf(str.charAt(4)));
      }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(downTimer!=null){
            downTimer.stopDown();
        }
    }

    /**启动该页面
     *
     * @param context
     * @param orderId
     */
    public static void startPayActivity(Context context , String orderId){
        Intent intent = new Intent();
        intent.setClass(context , PayActivity.class);
        intent.putExtra(PARAM_ORDER_ID , orderId);
        context.startActivity(intent);
    }
}
